﻿using Common.Api.Client;
using Common.Api.Dtos;
using Cyss.Core;
using CyssBlazor.Shared.Components;
using Microsoft.AspNetCore.Components;
using System.Threading.Tasks;

namespace CyssBlazor.Shared.Pages.Manager.Settings
{
    public class BaseSettingComponent<TItem> : BaseComponent where TItem : BaseSettingModel, new()
    {

        [Parameter]
        public TItem Model { set; get; } = new TItem();

        /// <summary>
        /// 是否加载完成
        /// </summary>
        [Parameter]
        public bool IsLoadComplete { set; get; }

        /// <summary>
        /// 类型
        /// </summary>
        [Parameter]
        public SettingTypeModel SettingType { set; get; } = new SettingTypeModel();


        protected override async Task OnAfterRenderAsync(bool firstRender)
        {
            if (firstRender)
            {
                var operateResult = await CommonClientFactory.Setting.GetSettingByTypeName<TItem>(typeof(TItem).Name);
                IsLoadComplete = true;
                if (operateResult.IsSuccess)
                {
                    this.Model = operateResult.Data;
                    await this.AsyncRefresh();
                }
            }
            await base.OnAfterRenderAsync(firstRender);
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <returns></returns>
        public virtual async Task Save()
        {
            EditSettingModel edit = new EditSettingModel();
            edit.Setting = this.Model;
            edit.TableName = this.SettingType.TypeName;
            var operateResult = await CommonClientFactory.Setting.UpdateSetting(edit);
            if (operateResult.IsSuccess)
            {
                await this.Alert("保存成功!");
            }
            else
            {
                await this.Alert("保存失败!" + operateResult.Message);
            }
        }


    }
}
